<template>
  <div class="dataManagement">
    <MetaSearchForm @on-search="tableSearch">
      <el-form ref="dataManagement_form" :model="searchData" label-width="80px">
        <el-form-item label="设备" class="dataManagement_searchFromItem">
          <el-select v-model="searchData.equipmentid" placeholder="请选择设备">
            <el-option
              v-for="item in equipmentList"
              :key="item.id"
              :label="item.equipmentname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采集时间" class="dataManagement_searchFromItem">
          <el-date-picker
            v-model="searchData.dateBetween"
            type="datetimerange"
            range-separator="-"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </MetaSearchForm>
    <MetaPageTable
      ref="dataManagementTable"
      :autoReqFirst="false"
      class="dataManagement_table"
      table-title="数据管理"
      :needCheckbox="true"
      :need-checkbox="false"
      :is-auto-req="true"
      :req-url="reqUrl"
      :req-data="searchDataForTable"
      req-method="post"
      :display-item="displayItem"
      :btn-group="btnGroup"
      @btnClick="tableBtnClick"
      :line-btn-group="lineBtnGroup"
      @lineBtnClick="tableLineBtnClick"
    />
    <el-dialog
      v-if="echartDialog"
      title="查看光谱曲线"
      :visible.sync="echartDialog"
      width="60%"
      center
      modal
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="echartForReflectivityBg">
        <div id="echartForReflectivity" class="echartForReflectivity"></div>
      </div>
    </el-dialog>
    <el-dialog
      v-if="exportDBDataFlag"
      title="导出定标数据"
      :visible.sync="exportDBDataFlag"
      width="60%"
      modal
      center
      :before-close="exportDBDataDialogClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="echartForReflectivityBg">
        <el-form
          ref="dbData_form"
          :model="exportDBData"
          label-width="150px"
          :rules="exportDBRules"
        >
          <el-form-item label="选择设备" prop="eid">
            <el-select
              v-model="exportDBData.eid"
              placeholder="请选择设备"
              multiple
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in equipmentList"
                :key="item.id"
                :label="item.equipmentname"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="dialogFooter">
        <el-button size="mini" @click="exportDBDataFlag = false">取消</el-button>
        <el-button type="primary" size="mini" @click="exportDBDataDialogSubmit()"
          >导出</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      v-if="dbDataImportFlag"
      title="文件上传"
      :visible.sync="dbDataImportFlag"
      width="40%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form label-width="80px" style="display: inline-block; width: 100%">
        <el-form-item label="设备" class="dataManagement_importFormItem">
          <el-select v-model="importEquipmentId" placeholder="请选择设备">
            <el-option
              v-for="item in equipmentList"
              :key="item.id"
              :label="item.equipmentname"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-upload
            style="float: right"
            v-show="importEquipmentId && importEquipmentId !== ''"
            :action="dbDataImportUrl"
            :file-list="dbDataFileList"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
            :headers="{
              'x-auth-token': token,
            }"
            :data="{
              equipmentId: importEquipmentId,
            }"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请上传excel文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import MetaPageTable from "../components/MetaPageTable";
import MetaSearchForm from "../components/MetaSearchForm";
import deepClone from "../utils/deepClone";
import utils from "../utils/utils";
export default {
  name: "dataManagement",
  components: {
    MetaPageTable,
    MetaSearchForm,
  },
  data() {
    return {
      dbDataImportFlag: false,
      dbDataFileList: [],
      exportDBDataFlag: false,
      importEquipmentId: "",
      exportDBData: {
        eid: "",
      },
      exportDialogFlag: false,
      echartDialog: false,
      searchData: {
        equipmentid: "",
        dateBetween: [],
      },
      searchDataForTable: {},
      token: localStorage.getItem("token"),
      reqUrl: process.env.PROGOO_GATE_WATER + "admin/collection",
      displayItem: [
        {
          label: "上传时间",
          prop: "transmissiontime",
        },
        {
          label: "采集位置（经度）",
          prop: "longitude",
        },
        {
          label: "采集位置（纬度）",
          prop: "latitude",
        },
        {
          label: "传感器数据",
          prop: "tdstem",
        },
        // {
        //   label: "传感器数据",
        //   type: "json",
        //   prop: "tdstem",
        //   parse: 2,
        //   props: [
        //     {
        //       key: "t",
        //       label: "温度",
        //       calculate: 0.01,
        //       retain: 2,
        //     },
        //     {
        //       key: "tds",
        //       label: "tds",
        //       retain: 1,
        //     },
        //     {
        //       key: "conductivity",
        //       label: "电导率",
        //       retain: 1,
        //     },
        //   ],
        // },
        {
          label: "采集类型",
          prop: "type",
          type: "if",
          format: {
            dc: "单次采集",
            ds: "定时采集",
            bzb: "标准板定标",
            adl: "暗电流定标",
            lx: "连续采集",
          },
        },
        {
          label: "采集时间",
          prop: "collecttime",
        },
      ],
      btnGroup: [
        {
          id: "replenishData",
          title: "补充反演数据",
        },
        {
          id: "exportRawData",
          title: "导出原始数据",
        },
        {
          id: "exportAllDataToday",
          title: "导出当天数据",
        },
        // {
        //   id: "exportDBData",
        //   title: "导出定标数据",
        // },
        // {
        //   id: "import",
        //   title: "导入定标数据",
        // },
      ],
      lineBtnGroup: [
        {
          id: "dnValue",
          title: "查看DN值",
        },
        {
          id: "reflectivity",
          title: "查看反射率",
        },
      ],
      itemExportData: {
        dateBetween: [],
      },
      rolesList: [],
      companyList: [],
      equipmentList: [],
      paramsList: [],
      echartForReflectivity: null,
      exportDBRules: {
        eid: [{ required: true, message: "请选择设备", trigger: "change" }],
      },
      chartXaxis: [],
    };
  },
  created() {
    window.onresize = () => {
      if (this.echartForReflectivity) {
        this.echartForReflectivity.resize();
      }
    };
  },
  mounted() {
    this.getEquipmentList(() => {
      if (this.equipmentList.length > 0) {
        //加载记忆的设备 Ray
        if(this.$route.meta.remember) {
          let equId = localStorage.getItem('dataCenterEquipmentId')
          if(equId && equId !== '') {
            this.searchData.equipmentid = equId
          }else {
            this.searchData.equipmentid = this.equipmentList[0].id
          }
        }else {
          this.searchData.equipmentid = this.equipmentList[0].id
        }

        // this.searchData.equipmentid = this.equipmentList[0].id;
        this.searchData.dateBetween = [];
        let nowDay = utils.formatDate("yyyy-MM-dd", new Date());
        this.searchData.dateBetween.push(nowDay + " 00:00:00");
        this.searchData.dateBetween.push(nowDay + " 23:59:59");
        this.tableSearch();
      }
    });
  },
  methods: {
    getEquipmentList(callback) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/equipment/user",
        method: "post",
        data: {},
      }).then((res) => {
        if (res.data.code === 200) {
          this.equipmentList = res.data.result;
          callback();
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    tableLineBtnClick(item) {
      if (item.button === "reflectivity") {
        this.echartDialog = true;
        this.$nextTick(() => {
          this.initEchart(item.rows, "reflectivity");
        });
      } else if (item.button === "dnValue") {
        this.echartDialog = true;
        this.$nextTick(() => {
          this.initEchart(item.rows, "dnValue");
        });
      }
    },
    initEchart(itemDatas, key) {
      let dList = [];
      let chartTitle = "";
      let chartText = "";
      if (key == "dnValue") {
        dList = itemDatas.dndata.split(",");
        chartTitle = "DN值";
        chartText = "DN值";
      } else if (key == "reflectivity") {
        dList = itemDatas.reflectivity.split(",");
        chartTitle = "反射率";
        chartText = "反射率";
      }
      // let reflectivityList = itemDatas.reflectivity.split(",")
      let refDataList = [];
      for (let i in dList) {
        refDataList.push(parseFloat(dList[i]));
      }
      let echarts = require("echarts");
      let chartDoc = document.getElementById("echartForReflectivity");
      this.echartForReflectivity = echarts.init(chartDoc);
      this.echartForReflectivity.setOption({
        title: {
          text: chartTitle,
          x: "center",
          y: "top",
        },
        tooltip: {
          trigger: "axis",
        },
        grid: {
          left: "5%",
          bottom: "5%",
          top: "10%",
          height: "80%",
          right: "2%",
          show: true,
          // containLabel: true
        },
        xAxis: {
          type: "category",
          axisLabel: {
            show: true,
            fontSize: 10,
          },
          boundaryGap: false,
          data: this.chartXaxis,
        },
        yAxis: {
          type: "value",
          axisLabel: {
            show: true,
            fontSize: 10,
          },
          scale: true,
        },
        series: [
          {
            name: chartText,
            type: "line",
            stack: chartText,
            smooth: true,
            data: refDataList,
          },
        ],
      });
      this.$nextTick(() => {
        this.echartForReflectivity.resize();
      });
    },
    tableBtnClick(item) {
      if (item.button === "export") {
        // const url = window.URL.createObjectURL(new Blob([data.data]))
        // const link = document.createElement('a')
        // link.style.display = 'none'
        // link.href = url
        // link.setAttribute('download', '订单信息清单.xlsx')
        // document.body.appendChild(link)
        // link.click()
        // document.body.removeChild(link)
        // window.open(
        //   baseAPI.PROD_PRODUCT_PROCESS_NODE_EXPORTLIST +
        //     '?ldcProdProductProcessId=' +
        //     params.ldcProdProductProcessId +
        //     '&Authorization=Bearer' +
        //     localStorage.getItem('access_token')
        // )
      } else if (item.button === "exportRawData") {
        if (this.equipmentList.length <= 0) {
          return;
        }
        let params = {};
        params.datestart = this.searchDataForTable.datestart
          ? this.searchDataForTable.datestart
          : "";
        params.dateend = this.searchDataForTable.dateend
          ? this.searchDataForTable.dateend
          : "";
        params.equipmentid = this.searchDataForTable.equipmentid
          ? this.searchDataForTable.equipmentid
          : "";
        // params.page = 1
        // params.limit = 99999999

        // this.$fetch({
        //   url: process.env.PROGOO_GATE_WATER + "admin/collection",
        //   method: "post",
        //   data: params
        // }).then(res => {
        //   // this.doExportData(res.data.result.content)
        // })
        let eName = "";
        for (let i in this.equipmentList) {
          if (this.searchDataForTable.equipmentid === this.equipmentList[i].id) {
            eName = this.equipmentList[i].equipment_name;
            let start = utils.getStrByUnderlineBefore(
              this.searchDataForTable.datestart,
              " "
            );
            let end = utils.getStrByUnderlineBefore(this.searchDataForTable.dateend, " ");
            if (this.searchDataForTable.datestart && this.searchDataForTable.dateend) {
              if (start == end) {
                eName += "(" + start + ")";
              } else {
                eName += "(" + start + " - " + end + ")";
              }
            }
            break;
          }
        }
        let token = localStorage.getItem("token");
        this.axios({
          method: "post",
          url: process.env.PROGOO_GATE_WATER + "admin/collectionExport",
          data: params,
          // token
          headers: {
            "x-auth-token": token,
          },
          responseType: "blob",
        }).then((res) => {
          if (res.data.code && res.data.code == 400) {
            this.$notify.error({
              title: "错误",
              message: res.data.message,
            });
            return;
          }
          const url = window.URL.createObjectURL(new Blob([res.data]));
          const link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute(
            "download",
            eName == "" ? "光谱数据.xlsx" : "光谱参数_" + eName + ".xlsx"
          );
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        });
      } else if (item.button === "replenishData") {
        // 新增数据补充接口 liudechen
        if (item.rows.length <= 0) {
          this.$notify.warning({
            title: "警告",
            message: "请选择数据",
          });
          return;
        }
        let time = item.rows[0].transmissiontime;
        for (let i in item.rows) {
          if (time !== item.rows[i].transmissiontime) {
            this.$notify.warning({
              title: "警告",
              message: "请选择相同采集时间的一组数据",
            });
            return;
          }
        }
        // let param = {}
        // param.eid = this.searchDataForTable.equipmentid
        // param.date = time
        // param.collections = item.rows

        this.$fetch({
          url: process.env.PROGOO_GATE_WATER + "admin/reflectivity/bc",
          method: "post",
          data: item.rows,
        }).then((res) => {
          if (res.data.code === 200) {
            this.$notify.success({
              title: "成功",
              message: "补充成功",
            });
          } else {
            this.$notify.error({
              title: "错误",
              message: res.data.message,
            });
          }
        });
      } else if (item.button === "exportAllDataToday") {
        let token = localStorage.getItem("token");
        let username = localStorage.getItem("username");
        this.axios({
          method: "post",
          url: process.env.PROGOO_GATE_WATER + "admin/all/rawData",
          data: {
            username: username,
          },
          // token
          headers: {
            "x-auth-token": token,
          },
          responseType: "blob",
        }).then((res) => {
          if (res.data.code && res.data.code == 400) {
            this.$notify.error({
              title: "错误",
              message: res.data.message,
            });
            return;
          }
          const url = window.URL.createObjectURL(new Blob([res.data]));
          const link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          let today = new Date();
          link.setAttribute(
            "download",
            today.getFullYear() +
              "-" +
              (today.getMonth() + 1) +
              "-" +
              today.getDate() +
              "_光谱数据.xlsx"
          );
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        });
      } else if (item.button === "exportDBData") {
        this.exportDBDataFlag = true;
      } else if (item.button === "import") {
        this.$confirm("定标数据会影响数据结果，请反复确认数据", "确认导入定标数据?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.dbDataFileList = [];
          this.dbDataImportUrl = process.env.PROGOO_GATE_WATER + "admin/collectionDB/import";
          this.importEquipmentId = "";
          this.dbDataImportFlag = true;
        });
      }
    },
    doExportData(resData) {
      let equip = {};
      let wave = {};
      for (let i in this.equipmentList) {
        equip[this.equipmentList[i].id] = this.equipmentList[i].equipmentname;
        wave[this.equipmentList[i].id] = this.equipmentList[i].wavelength;
      }
      let enumType = {
        adl: "暗电流",
        bzb: "标准版",
        dc: "单次采集",
        lx: "连续采集",
        ds: "定时采集",
      };
      let header = [
        "设备名称",
        "dn值",
        "反射率",
        "指令",
        "经度",
        "纬度",
        "采集类型",
        "采集时间",
        "备注",
      ];
      let exData = [];
      for (let i in resData) {
        let itemList = [];
        itemList.push(equip[resData[i].equipmentid]);
        itemList.push(resData[i].dndata);
        itemList.push(resData[i].reflectivity);
        itemList.push(resData[i].dnvalue);
        itemList.push(resData[i].longitude);
        itemList.push(resData[i].latitude);
        itemList.push(enumType[resData[i].type]);
        itemList.push(resData[i].transmissiontime);
        itemList.push(resData[i].remark);
        exData.push(itemList);
      }
      if (resData.length > 0) {
        let waveList = [];
        waveList.push("中心波长");
        waveList.push(wave[resData[0].equipmentid]);
        exData.push(waveList);
      }

      let title = "原始数据";
      this.$export_json_to_excel(header, exData, title);
    },
    tableSearch() {
      let param = {};
      for (let key in this.searchData) {
        if (key === "dateBetween") {
          param.datestart =
            this.searchData[key] && this.searchData[key].length > 0
              ? this.searchData[key][0]
              : "";
          param.dateend =
            this.searchData[key] && this.searchData[key].length > 0
              ? this.searchData[key][1]
              : "";
        } else {
          param[key] = this.searchData[key];
        }
      }
      this.searchDataForTable = param;
      for (let i in this.equipmentList) {
        if (param.equipmentid === this.equipmentList[i].id) {
          this.chartXaxis = this.equipmentList[i].wavelength.split(",");
        }
      }
      
      //设备确认选择后存储后 Ray
      localStorage.setItem("dataCenterEquipmentId", this.searchDataForTable.equipmentid)
      this.$nextTick(() => {
        this.$refs.dataManagementTable.formDataInit(true);
      });
    },
    getBeforeDate(n) {
      const d = new Date();
      let mon = d.getMonth() + 1;
      const day = d.getDate();
      if (day <= n) {
        if (mon > 1) {
          mon = mon - 1;
        } else {
          mon = 12;
        }
      }
      d.setDate(d.getDate() - n);
      return d;
    },
    exportDBDataDialogClose(done) {
      this.exportDBData = {
        eid: "",
      };
      done();
    },
    exportDBDataDialogSubmit() {
      this.$refs["dbData_form"].validate((valid) => {
        if (valid) {
          let token = localStorage.getItem("token");
          this.axios({
            method: "post",
            url: process.env.PROGOO_GATE_WATER + "admin/collectionDB/download",
            data: this.exportDBData.eid,
            // token
            headers: {
              "x-auth-token": token,
            },
            responseType: "blob",
          }).then((res) => {
            if (res.data.code && res.data.code == 400) {
              this.$notify.error({
                title: "错误",
                message: res.data.message,
              });
              return;
            }
            const url = window.URL.createObjectURL(new Blob([res.data]));
            const link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            link.setAttribute("download", "定标数据.xlsx");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            this.exportDBDataFlag = false;
          });
        } else {
          return false;
        }
      });
    },
    beforeUpload(file) {
      let excelfileExtend = ".xlsx.xls"; //设置文件格式
      let fileExtend = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
      if (excelfileExtend.indexOf(fileExtend) <= -1) {
        this.dbDataFileList = [];
        this.$message.error("文件格式错误");
        return;
      }
    },
    uploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.dbDataFileList = [];
        this.$notify({
          title: "成功",
          message: "导入成功",
          type: "success",
        });
        this.dbDataImportFlag = false;
        this.initPointData(this.pointData.pointFid);
      } else {
        this.dbDataFileList = [];
        this.$notify.error({
          title: "错误",
          message: response.message,
        });
      }
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.dataManagement {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px;
  overflow-y: scroll;
  .dataManagement_table {
    width: 100%;
    overflow-y: unset;
  }
  .echartForReflectivityBg {
    width: 100%;
    height: 400px;
    box-sizing: border-box;
    padding: 10px 20px;
    .echartForReflectivity {
      width: 100%;
      height: 100%;
    }
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
  .roleChooseSelect {
    width: 100%;
  }
  .dataManagement_searchFromItem {
    float: left;
  }
  .dataManagement_importFormItem {
    float: left;
    width: 100%;
  }
}
</style>
